<?php
require_once("../util/validate.php");
$config_file = parse_ini_file("../../properties/config.ini");
$include_path = "../";
include_once("../util/db_manager.php");
include_once("../util/log_writer.php");
$lw = LogWriter::getInstance("../../properties/log4php-level2.properties");
$error = false;
try {
	$client_ip = $_POST['client_ip'];
	if ($client_ip != null) {
		//validate form
		$lw->debug("Validating");
		$msg = validateContactMe($_POST['yourname'],$_POST['replyto'],$_POST['subject'],$_POST['message'],$_POST['recaptcha_challenge_field'],$_POST['recaptcha_response_field'],$client_ip,$config_file["recaptcha_private_key"],$config_file["defensio_key"]);
		if ($msg != null) {
			$lw->debug("errors");
			$error = true;
		} else {
			//start db transaction
			$lw->debug("no error. getting db manager");
			$dbManager = DBManager::getInstance($config_file);
			$lw->debug("getting connection");
			$conn = $dbManager->fetchConnection();
			try {
				//submit the information
				$query = "INSERT INTO emails(ip_address,name,reply_to,sbj,message) values('" . 
										$client_ip . "','" .
										mysql_escape_string(htmlspecialchars(trim($_POST['yourname']))) . "','" .
										mysql_escape_string(htmlspecialchars(trim($_POST['replyto']))) . "','" .
										mysql_escape_string(htmlspecialchars(trim($_POST['subject']))) . "','" .
										mysql_escape_string(htmlspecialchars(trim($_POST['message']))) . "')";
				$lw->debug(" firing " . $query);
				$result = $dbManager->processQuery($query,$conn);
				$lw->debug("sending email");
				//send the email
				$hreaders = "From: " . $config_file["mail_from"] . "\r\n" .
							"Reply-To: " . htmlspecialchars(trim($_POST['yourname'])) . " <" . htmlspecialchars(trim($_POST['replyto'])) . ">" . "\r\n" .
							"X-Mailer: PHP/" . phpversion();
				mail("wetchlorophylls@gmail.com",htmlspecialchars(trim($_POST['subject'])),wordwrap(htmlspecialchars(trim($_POST['message'])),70),$headers);
				$lw->debug("closing connection");
				$dbManager->releaseConnection($conn);
				$lw->debug("done");
				$msg = "Got it! Thank you for contacting me. I'll respond as soon as possible.";
			} catch(Exception $e1) {
				$lw->error($e1);
			}
		}
	}
} catch (Exception $e) {
	$lw->error($e);
	$error = true;
	$msg = $e->getMessage();
} 
	include("form_submit_message_parser.php");
?>
